package com.gl.wxstore.sys.controller;

import java.util.List;

import com.gl.wxstore.common.BaseController;
import com.gl.wxstore.common.model.StoreReceiveAddress;
import com.gl.wxstore.common.model.SysUser;
import com.gl.wxstore.sys.service.SysUserService;
import com.jfinal.aop.Duang;

/**
 * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 *
 */
public class SysUserController extends BaseController {

	/**
	 * JFinal 中的 AOP 被划分为控制层 AOP 以及业务层
	 * AOP，如果要在业务层使用AOP，需要通过Duang.duang()或Enhancer.enhance()进行增强！
	 */
	private SysUserService userService = Duang.duang(SysUserService.class);

	// @Before(ArticleInterceptor.class)
	// public void list() {
	// // 创建单例的ArticleService对象
	// // ArticleService articleService1 = Duang.duang("key",
	// ArticleService.class);
	// // ArticleService articleService2 = Duang.duang("key",
	// ArticleService.class);
	// // System.out.println(articleService1 == articleService2);
	// setAttr("article", "一篇文章.");
	// render("list.jsp");
	// }

	public void login() {
		SysUser user = SysUser.dao.login(getPara("code"), getPara("password"));
		if (user != null) {
			setSessionAttr("user", user);
			redirect("/product/listProduct.html");
		} else {
			redirect("/index.html");
		}
	}

	public void logout() {
		removeSessionAttr("user");
		redirect("/index.html");
	}

	public void userInfo() {
		SysUser user = (SysUser) getSessionAttr("user");

		StoreReceiveAddress receiveAddress = StoreReceiveAddress.dao
				.getFirst(user.getId());
		setAttr("receiveAddress", receiveAddress);
		render("/views/store/userinfo.jsp");
	}

	public void listAddress() {
		SysUser user = (SysUser) getSessionAttr("user");

		// FIXME session里 还没东西
		List<StoreReceiveAddress> addressList = StoreReceiveAddress.dao
				.list(user.getId());
		setAttr("addressList", addressList);
		render("/views/store/address.jsp");

	}

	public void addAddress() {
		StoreReceiveAddress address = getModel(StoreReceiveAddress.class,
				"address");
		StoreReceiveAddress.dao.add(address);

		redirect("/user/listAddress.html");

	}

	public void deleteAddress() {
		String id = getPara("id");
		StoreReceiveAddress.dao.deleteById(id);
		redirect("/user/listAddress.html");
	}
}
